//
//  SDSubdivideViewController.m
//  SuperDoctor
//
//  Created by 李忠 on 7/9/16.
//  Copyright © 2016 SD. All rights reserved.
//

#import "SDSubdivideViewController.h"
#import "SDNetWorkTool.h"
#import "SDSubdivideModel.h"
#import "SVProgressHUD.h"
#import "NSString+SDPinyin.h"
#import "SDSyndromeCell.h"


@interface SDSubdivideViewController ()<UITableViewDelegate, UITableViewDataSource>

//存储SDSubdivideModel模型数据的数组
@property (nonatomic, strong) NSArray<SDSubdivideModel *> *subdivides;
//tableView
@property (nonatomic, strong) UITableView *tableView;

//用于传输被选择的类
@property (nonatomic, strong) NSMutableArray *diseaseArrM;

//保存搜索结果
@property (nonatomic, strong) NSMutableArray *searchResultM;

//保存搜索结果的状态
@property (nonatomic, assign, getter=isSearchState) BOOL searchState;


@end

@implementation SDSubdivideViewController

- (void)viewDidLoad{
    [super viewDidLoad];
    
    [self setupUI];
    [self checkCellType];
    
}

- (void)setupUI{
    
    self.navigationItem.title = self.titleName;
    [self.view addSubview:self.tableView];
    
    self.tableView.tableFooterView = [[UIView alloc] init];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
}

- (void)checkCellType{
    switch (self.patientType) {
            
        case SDPatientSubdivide:
            [self loadSubdivides];
            
            break;
            
        case SDPatientSyndrome:{
            
            [self loadSyndrome];
        }
            break;
        case SDPatientSureWay:
            self.subdivides = [SDSubdivideModel getSureWay];
            break;
    }
    
}

- (void)loadSubdivides{
    
    UITextField *searchField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
    searchField.placeholder = @"输入关键字";
    searchField.borderStyle = UITextBorderStyleRoundedRect;
    [searchField addTarget:self action:@selector(darkSearch:) forControlEvents:UIControlEventEditingChanged];
    self.navigationItem.titleView = searchField;

    
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    [SVProgressHUD showWithStatus:@""];
    [SDSubdivideModel subdividesWithSccucess:^(NSArray *array) {
        
        self.subdivides = array;
        [SVProgressHUD dismiss];
        
    } withError:^(NSError *error) {
        
        [SVProgressHUD setMinimumDismissTimeInterval:2];
        [SVProgressHUD showErrorWithStatus:@"数据无法加载"];
        
    }];
    
    
}

- (void)loadSyndrome{
    self.subdivides = [SDSubdivideModel getSydorme];
    [self.tableView registerClass:[SDSyndromeCell class] forCellReuseIdentifier:@"cell"];
    
    UIButton *btn = [[UIButton alloc] init];
    [btn setTitle:@"确定" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(clickSure) forControlEvents:UIControlEventTouchUpInside];
    [btn sizeToFit];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
}
#pragma mark
#pragma mark - tableView 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    //判断所搜结果数组中是否有结果
    NSInteger count = self.searchResultM.count;
    if (self.isSearchState) {
        if (count > 0) {
            
            return count;
        }else{
            
            return 0;
        }
        
    }else{
        
         return self.subdivides.count;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SDSubdivideModel *model = self.subdivides[indexPath.row];
    
    if (self.patientType == SDPatientSyndrome) {
        SDSyndromeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        cell.diseaseArrM = self.diseaseArrM;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        return cell;
    }else{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        //如果搜索结果中有了数据，就不在往下执行了
        if (self.searchResultM.count > 0 || self.isSearchState) {
            SDSubdivideModel *model = self.searchResultM[indexPath.row];
            cell.textLabel.text = model.ci3_name;
            return cell;
        }
        
        if (self.searchResultM.count > 0 || self.isSearchState) {
            SDSubdivideModel *model = self.searchResultM[indexPath.row];
            cell.textLabel.text = model.ci3_name;
            return cell;
        }
        if (self.patientType == SDPatientSubdivide) {
            
            cell.textLabel.text = model.ci3_name;
            
        }else if(self.patientType == SDPatientSureWay){
            
            cell.textLabel.text = model.ci3_name;
        }

        return cell;

    }
}



- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    //MARK : 定义SDPatientSyndrome表格方法
    if (self.patientType == SDPatientSyndrome){
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
        label.numberOfLines = 2;
        label.font = [UIFont systemFontOfSize:13];
        label.textColor = [UIColor redColor];
        label.text = @"注意：1.下面的cell一个都不能少，测试复用 2.点击cell 不能做事情，点击btn更改文字和字体，再点击可以取消";
        return label;
    }
    return nil;
    
}
- (CGFloat )tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (self.patientType == SDPatientSyndrome) return 40;
    return 0.01;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.patientType == SDPatientSyndrome)return;
    
    SDSubdivideModel *model = self.subdivides[indexPath.row];
    NSString *string = model.ci3_name;
   
    [self.diseaseArrM addObject:string];
    
    if (_famousDoctorsBlock) {
        _famousDoctorsBlock(self.diseaseArrM, self.patientType);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark

#pragma mark - 监听方法

- (void)clickCellButton:(UIButton *)sender{
    
    sender.selected = !sender.isSelected;
    
    UITableViewCell *cell = (UITableViewCell *)(sender.superview).superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSInteger index = indexPath.row;
    SDSubdivideModel *model = self.subdivides[index];
    
    if (sender.isSelected) {
        
        model.selected = YES;
        [self.diseaseArrM addObject:model.ci3_name];
    }else{
        model.selected = NO;
        [self.diseaseArrM removeObject:model.ci3_name];
    }
    
}
=======
#pragma mark - 点击确定后把并发症数据返回
>>>>>>> 422d77f26e4c7c6474ccd8ea8680334d98481c8f
- (void)clickSure{
    if (_famousDoctorsBlock) {
        _famousDoctorsBlock(self.diseaseArrM, self.patientType);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark
#pragma mark - 搜索核心
- (void)darkSearch:(UITextField *)sender{
   
    NSString *string = sender.text;
    
    if (self.searchResultM.count>0) {
        
        [self.searchResultM removeAllObjects];
    }
    
    //开始搜索
    NSString *key = string.lowercaseString;
    NSMutableArray *tempArr = [NSMutableArray array];
    
    if (![key isEqualToString:@""] && ![key isEqual:[NSNull null]] && key != nil) {
        
        [self.subdivides enumerateObjectsUsingBlock:^(SDSubdivideModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            
            //担心框架有时候会误转，再次都设置转为小写
            NSString *name = obj.ci3_name.lowercaseString;
            NSString *namePinyin = obj.namePinYin.lowercaseString;
            NSString *nameFireLetter = obj.nameFirstLetter.lowercaseString;
            
            NSRange rang1 = [name rangeOfString:key];
            if (rang1.length>0) {
                
                [tempArr addObject:obj];
            }else{
                
                if ([nameFireLetter containsString:key]) {
                    
                    [tempArr addObject:obj];
                    
                }else{
                    
                    if ([nameFireLetter containsString:[key substringToIndex:1]]) {
                        
                        if ([namePinyin containsString:key] ) {
                            [tempArr addObject:obj];
                        }
                    }
                }
            }
        }];
        
        [tempArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if (![self.searchResultM containsObject:tempArr[idx]]) {
                
                [self.searchResultM addObject:tempArr[idx]];
            }
        }];
        
        self.searchState = YES;
    }else{
        
        self.searchState = NO;
    }
    
    [self.tableView reloadData];
}


#pragma mark
#pragma mark - 懒加载控件
- (UITableView *)tableView{
    if ( _tableView == nil) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
    }
    return _tableView;
}
- (NSMutableArray *)diseaseArrM{
    if (_diseaseArrM == nil) {
        _diseaseArrM = [NSMutableArray array];
    }
    return _diseaseArrM;
}
- (NSMutableArray *)searchResultM{
    if (_searchResultM == nil) {
        _searchResultM = [NSMutableArray array];
    }
    return _searchResultM;
}

#pragma mark
#pragma mark - 重写subdivdes的set方法
- (void)setSubdivides:(NSArray<SDSubdivideModel *> *)subdivides{
    _subdivides = subdivides;
    [self.tableView reloadData];
}


@end
